package com.borderbears.backend.media;
import java.util.List;
import java.util.Vector;

import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class MediaTreeModel implements TreeModel {

	private final List<TreeModelListener> listeners = new Vector<TreeModelListener>();

	private MediaNode root;

	public MediaTreeModel() {
	}

	public void setRoot(final MediaNode root) {
		this.root = root;
		fireTreeStructureChanged();
	}

	public Object getRoot() {

		return root;
	}

	public Object getChild(final Object parent, final int index) {
		return ((MediaNode) parent).getChildren().get(index);
	}

	public int getChildCount(final Object parent) {
		return ((MediaNode) parent).getChildren().size();
	}

	public boolean isLeaf(final Object node) {
		return !((MediaNode) node).isDirectory();
	}

	public void valueForPathChanged(final TreePath path, final Object newValue) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	public int getIndexOfChild(final Object parent, final Object child) {
		return ((MediaNode) parent).getChildren().indexOf(child);
	}

	public void addTreeModelListener(final TreeModelListener l) {
		if (!listeners.contains(l)) {
			listeners.add(l);
		}
	}

	public void removeTreeModelListener(final TreeModelListener l) {
		listeners.remove(l);
	}

	public void fireTreeStructureChanged() {
		final MediaNode[] path = {root};
		final TreeModelEvent ev = new TreeModelEvent(this, path);
		for (final TreeModelListener l : listeners) {
			l.treeStructureChanged(ev);
		}
	}



}